/**
 * Copyright 2007 Jason Horman, Pete Aykroyd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.functor.expression;

import java.util.*;

/** Or's a number of {@link org.functor.UnaryPredicate unary predicates} together. */
public class OrImpl extends AbstractJunction implements Or {
	public OrImpl() {
		this(new ArrayList<PredicateExpression>());
	}

	public OrImpl(PredicateExpression ... predicates) {
		this(Arrays.asList(predicates));
	}

	public OrImpl(List<PredicateExpression> predicates) {
		super(optimizeOrs(predicates));
	}

	private static List<PredicateExpression> optimizeOrs(List<PredicateExpression> predicates) {
		List optimized = new ArrayList();
		for (PredicateExpression predicate : predicates) {
			if (predicate instanceof Or)
				optimized.addAll(((Or)predicate).getPredicates());
			else if (!predicate.isAlwaysFalse())
				optimized.add(predicate);
		}

		return optimized;
	}

	public OrImpl(Collection<PredicateExpression> predicates) {
		this(new ArrayList(predicates));
	}

	public boolean isAlwaysTrue() {
		for (PredicateExpression expression : getPredicates())
			if (expression.isAlwaysTrue())
				return true;
		return false;
	}

	public boolean isAlwaysFalse() {
		for (PredicateExpression expression : getPredicates())
			if (!expression.isAlwaysFalse())
				return false;
		return true;
	}

	protected String getJoiningKeyword() {
		return " OR ";
	}
}
